﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MMITDomain.Abstract;
using MMITDomain.Entities;
using MMITWeb.Models;
using MMITCore.Logging;
using MMITCore.Abstract;

namespace MMITWeb.Controllers
{
    public class AccountController : Controller
    {
        IAccountRepository accountRepository;
        ICustomerRepository customerRepository;
        ITransactionRepository transactionRepository;
        ICurrencyRepository currencyRepository;
        ILogger<SynkronLogger> _logger;

        public AccountController(IAccountRepository accountRepository, ICustomerRepository customerRepository, 
            ITransactionRepository transactionRepository, ICurrencyRepository currencyRepository, ILogger<SynkronLogger> logger)
        {
            this.accountRepository = accountRepository;
            this.customerRepository = customerRepository;
            this.transactionRepository = transactionRepository;
            this.currencyRepository = currencyRepository;
            _logger = logger;
        }
        
        [Authorize]
        public ViewResult GetAccounts()
        {
            try
            {
                var accounts = accountRepository.GetCustomerAccounts(customerRepository.Customers.
                    Where(c => c.Username == User.Identity.Name).SingleOrDefault<Customer>());
                
                //get all transactions for customer.
                var transactions = transactionRepository.GetCustomerTransactions(customerRepository.Customers.
                    Where(c => c.Username == User.Identity.Name).SingleOrDefault<Customer>()).ToList();

                var model = new List<AccountTransactionsViewModel>();
                foreach (var item in accounts)
                {
                    model.Add(new AccountTransactionsViewModel {Account = item, 
                        Transactions = transactions.FindAll(o => o.SenderId == item.Id) });
                }

                _logger.WriteInformation(4000000, () => string.Format("Customer Accounts Retrieval Successful {0}", User.Identity.Name),
                    new Dictionary<string, object> { { string.Format("Action Method : {0}", this.ControllerContext.RouteData.GetRequiredString("action")), _logger.Desc(this.ControllerContext) },
                        {"Account Transactions :", _logger.Desc(model)}
                    });
                return View(model);
            }
            catch (Exception Ex)
            {
                _logger.WriteError(4000001, () => string.Format("Exception Retrieving : [{0}] Customer Account info: {1}", User.Identity.Name),Ex,
                   new Dictionary<string, object>{{string.Format("Action Method : {0}",this.ControllerContext.RouteData.GetRequiredString("action")), _logger.Desc(this.ControllerContext)}});
            }

            return View();
        }

        [Authorize]
        public ViewResult AddAccount()
        {
            var currencies = from t in currencyRepository.Currencies.ToList()
                             select new Telerik.Web.Mvc.UI.DropDownItem
                             {
                                 Text = t.Name,
                                 Value = t.Id.ToString()
                             };
            AccountViewModel model = new AccountViewModel { Currencies = currencies };
 
            return View(model);
        }

        [HttpPost]
        public ActionResult AddAccount(AccountViewModel model, int Id)
        {
            var currencies = from t in currencyRepository.Currencies.ToList()
                             select new Telerik.Web.Mvc.UI.DropDownItem
                             {
                                 Text = t.Name,
                                 Value = t.Id.ToString()
                             };

            try
            {
                if (ModelState.IsValid)
                {
                    //Get Currently Logged in Customer..
                    var customer = customerRepository.GetCustomerByUsername(HttpContext.User.Identity.Name);
                    //Add A New Account...
                    var objAccount = new Account
                    {
                        AccountTypeId = (int)AccountType.AccountTypes.Customer,
                        Name = model.AccountName,
                        CustomerId = customer.Id,
                        CurrencyId = Id,
                        ActualBalance = 0.00M,
                        AvailableBalance = 0.00M,
                        Status = (int)AccountStatuses.Active
                    };

                    accountRepository.SaveAccount(objAccount);
                    ViewData["message"] = "Account Created Sucessfully..";

                    _logger.WriteInformation(4000002, () => string.Format("Customer Accounts Created Successfully {0}", User.Identity.Name),
                    new Dictionary<string, object> { { string.Format("Action Method : {0}", this.ControllerContext.RouteData.GetRequiredString("action")), _logger.Desc(this.ControllerContext) } ,
                        {"Account Transactions :", _logger.Desc(model)},
                        {"Customer Info",_logger.Desc(customer)}, 
                        {"Account Info",_logger.Desc(objAccount)}
                    });
                    return RedirectToAction("Success");
                    
                }
            }
            catch (Exception Ex)
            {
                //Log Exception...
                _logger.WriteError(4000003, () => string.Format("Error Adding New Customer Wallet"), Ex,
                   new Dictionary<string, object> { { string.Format("Action Method : {0}", this.ControllerContext.RouteData.GetRequiredString("action")), _logger.Desc(this.ControllerContext) } 
                   });
            }

            return View(new AccountViewModel { Currencies = currencies});
        }

        public ViewResult Success()
        {
            return View();
        }
    }
}
